#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include <cstring>
#include "mtx.hpp"
#include "model.hpp"
#include <time.h>
using namespace std;
//创建线程数量
#define NUMPTHREAD_T 6
//函数指针
typedef void (*func)(int);
//函数声明
void product(int number);
void custcom(int number);
proCust<int> mod;
//判断是生产者还是消费者
struct Pro_or_cust
{
    int _number;
    string _name;
    func _product = product;
    func _custcom = custcom;
    Pro_or_cust(int number)
        : _number(number)
    {
    }
};
void product(int number)
{
    while (true)
    {
        //同步所有线程
        sleep(3);
        //随机生成数，项目中一般是做其他任务
        int val = rand() % 100000;
        cout << "我是生产者" << pthread_self() << "   " << number << endl;
        mod.push(val, number);
        sleep(1);
    }
}
void custcom(int number)
{
    while (true)
    {
        cout << "我是消费者" << pthread_self() << "   " << number << endl;
        int ret = mod.pop(number);
        //打印获得数据，一般也可以处理获取的数据
        cout << "我消费的数据" << ret << endl;
        sleep(1);
    }
}
void *enter(void *args)
{
    Pro_or_cust *p = (Pro_or_cust *)args;
    //判断是生产者还是消费者
    if (strcmp(p->_name.c_str(), "custcom") == 0)
        p->_custcom(p->_number);
    else
        p->_product(p->_number);
    delete p;
    return nullptr;
}
int main()
{
    srand((unsigned int)time(nullptr));
    pthread_t tid[NUMPTHREAD_T];
    for (int i = 0; i < NUMPTHREAD_T; i++)
    {
        Pro_or_cust *str = new Pro_or_cust(i + 1);
        if (i % 2 == 0)
            str->_name = "custcom";
        else
            str->_name = "product";
        pthread_create(tid + i, nullptr, enter, str);
        // sleep(1);
    }
    for (int i = 0; i < NUMPTHREAD_T; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    cout << "回收资源成功" << endl;
    return 0;
}